package com.jerry.secondkill.rabbitmq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jerry.secondkill.domain.SeckillOrder;
import com.jerry.secondkill.domain.User;
import com.jerry.secondkill.redis.RedisService;
import com.jerry.secondkill.service.GoodsService;
import com.jerry.secondkill.service.OrderService;
import com.jerry.secondkill.service.SeckillService;
import com.jerry.secondkill.vo.GoodsVo;

@Service
public class MQReceiver {

	private static Logger log = LoggerFactory.getLogger(MQReceiver.class);
		
	@Autowired
	RedisService redisService;
	@Autowired
	GoodsService goodsService;
	@Autowired
	OrderService orderService;
	@Autowired
	SeckillService seckillService;
		
	@RabbitListener(queues=MQConfig.QUEUE_SECKILL)
	public void receiveSeckillMessage(String message) {
		log.info("receive seckill message:"+message);
		
		//获取秒杀消息
		SeckillMessage mm  = redisService.stringToBean(message, SeckillMessage.class);
		User user = mm.getUser();
		long goodsId = mm.getGoodsId();
			
		//判断是否没有库存
		GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
	    int stock = goods.getStockCount();
	    if(stock <= 0) {
	    	return;
	    }
	    
	    //判断是否已经秒杀过或已经秒杀到了
	    SeckillOrder order = orderService.getSeckillOrderByUserIdGoodsId(user.getId(), goodsId);
	    if(order != null) {
	    	return;
	    }
	    
	    //减库存 下订单 写入秒杀订单
	    seckillService.seckill(user, goods);
	}
	
	@RabbitListener(queues=MQConfig.QUEUE)
	public void receiveDirect(String message) {
		log.info("receive direct message:"+message);
	}
		
	@RabbitListener(queues=MQConfig.QUEUE_1)
	public void receiveTopic1(String message) {
		log.info(" topic  queue1 message:"+message);
	}
		
	@RabbitListener(queues=MQConfig.QUEUE_2)
	public void receiveTopic2(String message) {
		log.info(" topic  queue2 message:"+message);
	}
		
	@RabbitListener(queues=MQConfig.QUEUE_3)
	public void receiveHeaderQueue(byte[] message) {
		log.info(" header  queue message:"+new String(message));
	}
		
		
}
